<template>
    <view class="page-box">
        <header class="header column rowCenter verCenter">
            <view class="pic">
                <image :src="counselorInfo.photo" mode="aspectFill"></image>
            </view>
            <text class="name">{{counselorInfo.name}}</text>
            <view class="stars row verCenter">
                <image src="../../static/star.png" mode="aspectFill" v-for="(v,i) in counselorInfo.star" :key="i"></image>
            </view>
            <view class="label row verCenter">
                <view class="box row rowCenter verCenter">从业{{counselorInfo.year}}年</view>
                <view class="box row rowCenter verCenter">{{counselorInfo.star}}星顾问</view>
            </view>
        </header>
        <view class="introduce bor">
            <view class="title">简介</view>
            <view class="text">{{counselorInfo.dec}}</view>
        </view>
        <view class="introduce">
            <view class="title">擅长</view>
            <view class="text">{{counselorInfo.specialty}}</view>
        </view>
        <view class="btn row rowCenter verCenter" @click="open()">咨询方案</view>
        <!-- 支付弹窗 -->
        <uni-popup ref="popup" background-color="#fff" borderRadius="20rpx 20rpx 20rpx 20rpx">
            <view class="popup-content column rowCenter verCenter">
                <view class="content column rowCenter verCenter">
                    <view class="ico">
                        <image src="../../static/pay.png" mode="aspectFill"></image>
                    </view>
                    <text class="t1">明星顾问为您一对一服务</text>
                    <view class="row">
                        <text class="t2">请支付</text>
                        <text class="t3">{{counselorInfo.price}}元</text>
                        <text class="t2">开启您的精准方案</text>
                    </view>
                    <view class="price row rowCenter verCenter">￥{{counselorInfo.price}}</view>
                    <view class="pay row rowCenter verCenter" @click="addCounselorOrder()">去支付</view>
                </view>
                <view class="iconfont icon-a-tubiaochangyongsousuo9" @click="close()"></view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
    import { API } from '@/util/api.js';
    export default {
        data() {
            return {
                id: '',
                counselorInfo: {},
                payPic: ''
            };
        },
        onLoad(options) {
            this.id = options.id;
        },
        onShow() {
            this.getData();
        },
        methods: {
            getData() {
                this.request(API.counselorInfo, 'GET', { id: this.id }, true).then(res => {
                    if (res.code === 0) {
                        this.counselorInfo = res.data;
                        uni.setNavigationBarTitle({
                            title: this.counselorInfo.name + ' - 明星顾问'
                        })
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 打开弹窗
             */
            open() {
                this.$refs.popup.open();
            },
            /**
             * 关闭弹窗
             */
            close() {
                this.$refs.popup.close();
            },
            /**
             * 创建顾问咨询支付订单
             */
            addCounselorOrder() {
                this.request(API.addCounselorOrder, 'POST', { counselor_id: this.counselorInfo.id, counselor_name: this.counselorInfo.name }, true).then(res => {
                    if (res.code === 0) {
                        this.payToDo(res.data.pay_id);
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 调取支付接口
             * @param {Object} pay_id
             */
            payToDo(pay_id) {
                this.request(API.payToDo, 'POST', { pay_id: pay_id }, true).then(res => {
                    if (res.code === 0) {
                        this.initWeixinPay(res.data, pay_id);
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 初始化微信支付
             * @param {Object} payParams 支付参数
             * @param {String} pay_id 支付ID
             */
            initWeixinPay(payParams, pay_id) {
                const onBridgeReady = () => {
                    WeixinJSBridge.invoke('getBrandWCPayRequest', payParams, (res) => {
                        if (res.err_msg === "get_brand_wcpay_request:ok") {
                            // 支付成功，开始轮询支付结果
                            this.startPollingPayResult(pay_id);
                        } else if (res.err_msg === "get_brand_wcpay_request:cancel") {
                            // 用户取消支付
                            uni.showToast({
                                title: '支付已取消',
                                icon: 'none'
                            });
                        } else {
                            // 其他情况，可能是支付失败或未知错误
                            uni.showToast({
                                title: '支付失败，请重试',
                                icon: 'none'
                            });
                        }
                    });
                };

                if (typeof WeixinJSBridge == "undefined") {
                    if (document.addEventListener) {
                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                    } else if (document.attachEvent) {
                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                    }
                } else {
                    onBridgeReady();
                }
            },
            /**
             * 开始轮询支付结果
             * @param {String} pay_id 支付ID
             */
            startPollingPayResult(pay_id) {
                let pollCount = 0;
                const maxPollCount = 10;
                const pollInterval = 1000; // 轮询间隔时间，单位毫秒

                // 使用 Promise 和 async/await 优化轮询逻辑
                const pollPayResult = async () => {
                    while (pollCount < maxPollCount) {
                        // 等待一段时间后再查询，避免立即查询
                        await new Promise(resolve => setTimeout(resolve, pollInterval));

                        try {
                            const result = await this.getPayOrder(pay_id);
                            if (result.success) {
                                // 支付成功，结束轮询
                                return true;
                            }
                        } catch (error) {
                            console.error('查询支付结果出错:', error);
                        }

                        pollCount++;
                    }
                    // 达到最大轮询次数，仍未成功
                    return false;
                };

                // 开始轮询
                pollPayResult().then(success => {
                    if (success) {
                        console.log('支付成功');
                        // 可以在这里添加支付成功后的逻辑
                    } else {
                        console.log('支付结果查询超时');
                        // 可以在这里添加查询超时的处理逻辑
                    }
                });
            },

            /**
             * 支付成功后定时任务查询支付结果
             * @param {Object} pay_id
             */
            getPayOrder(pay_id) {
                this.request(API.getPayOrder, 'GET', { pay_id: pay_id }, false).then(res => {
                    if (res.code === 0) {
                        this.payPic = res.data;
                        this.close();
                        uni.reLaunch({
                            url: '/pages/productMatch/success?pay_id=' + pay_id
                        });
                    }
                });
            }
        }
    };
</script>

<style scoped lang="scss">
    @import '@/assets/css/productMatch/chat.scss';
</style>